package br.com.carser.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import br.com.carser.exception.FacesValidatorException;

/**
 * Utility class to validate fields in front-end managed beans.
 * Are methods are statics.
 * 
 * TODO: Logger
 * 
 * @author Eduardo.
 */
public class ValidatorUtil {
	/**
	 * Email pattern.
	 */
	private static final String EMAIL_PATTERN = ".+@.+\\.[a-z]+";
	/**
	 * No meta-characters pattern.
	 */
	private static final String NO_META_CHARACTERS_PATTERN = "[^\\w\\.@-]";

	/**
	 * Validate string that have only letters..
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws FacesValidatorException
	 *             : if encounter some that are not letter.
	 */
	public static void validateString(FacesContext context,
			UIComponent component, Object value) throws FacesValidatorException {
		String word = (String) value;
		char[] c = word.toCharArray();
		for (char d : c) {
			if (Character.isDigit(d)) {
				throw new FacesValidatorException();
			}
		}
	}

	/**
	 * Validate numeric digits
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws FacesValidatorException
	 *             : if encounter some that are not numeric digit.
	 */
	public static void validateDigit(FacesContext context,
			UIComponent component, Object value) throws FacesValidatorException {
		String digit = (String) value;
		char[] c = digit.toCharArray();
		for (char d : c) {
			if (!Character.isDigit(d)) {
				throw new FacesValidatorException();
			}
		}
	}

	/**
	 * Validate email.
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws FacesValidatorException
	 *             : if no matches.
	 */
	public static void validateEmail(FacesContext context,
			UIComponent component, Object value) throws FacesValidatorException {
		String email = (String) value;
		Pattern p = Pattern.compile(EMAIL_PATTERN);
		Matcher m = p.matcher(email);
		if (!m.matches()) {
			throw new FacesValidatorException();
		}
	}

	/**
	 * Validate a string that have no meta characters.
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @throws FacesValidatorException
	 *             : if encounter some that are meta-character.
	 */
	public static void validateNoMetaChacters(FacesContext context,
			UIComponent component, Object value) throws FacesValidatorException {
		String email = (String) value;
		Pattern p = Pattern.compile(NO_META_CHARACTERS_PATTERN);
		Matcher m = p.matcher(email);
		if (m.find()) {
			throw new FacesValidatorException();
		}
	}
}
